package com.yupi.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.jayway.jsonpath.JsonPath;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.bizmq.BiConstant;
import com.yupi.springbootinit.bizmq.MyMessageProducer;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.manager.RedisLimiterManager;
import com.yupi.springbootinit.model.dto.ai.AiChatRequest;
import com.yupi.springbootinit.model.dto.chart.*;
import com.yupi.springbootinit.model.dto.file.UploadFileRequest;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.FileUploadBizEnum;
import com.yupi.springbootinit.model.enums.TaskStatusEnum;
import com.yupi.springbootinit.model.vo.BiResponse;
import com.yupi.springbootinit.model.vo.ChartVO;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 图表信息接口
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    private final String biCode = "btIWGSeT";

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private MyMessageProducer producer;
    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);

        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());

        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);

        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ChartVO> getChartVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chartService.getChartVO(chart, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ChartVO>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                         HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartService.getChartVOPage(chartPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ChartVO>> listMyChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                           HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartService.getChartVOPage(chartPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);

        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/genChartByAi")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest,
                                                 HttpServletRequest request) {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        User loginUser = userService.getLoginUser(request);

        ThrowUtils.throwIf(StrUtil.isBlank(goal), new RuntimeException("目标为空"));
        ThrowUtils.throwIf(ObjUtil.isNull(loginUser), new RuntimeException("用户未登录，请登陆！"));
        ThrowUtils.throwIf(StrUtil.isNotBlank(name) && name.length() > 100, new RuntimeException("名称过长"));

        // 数据校验
        String filename = multipartFile.getOriginalFilename();
        // 大小校验
        long size = multipartFile.getSize();
        // 10M限制
        final long maxSize = 1024 * 1024 * 10L;
        ThrowUtils.throwIf(size > maxSize, new RuntimeException("文件过大"));

        String suffix = FileUtil.getSuffix(filename);
        final List<String> validList = Arrays.asList("xls", "xlsx");
        ThrowUtils.throwIf(!validList.contains(suffix), new RuntimeException("所传文件非法"));

        // 针对每个用户进行限流
        Long userId = loginUser.getId();
        String limitPrefix = "mybi-genChartByAi";
        boolean isRateLimit = redisLimiterManager.doRateLimit(limitPrefix + userId.toString());
        ThrowUtils.throwIf(!isRateLimit, new RuntimeException("该账户已被限流，请24小时后再尝试！"));

        if (StringUtils.isNotBlank(chartType)) {
            goal = goal + "请使用：" + chartType;
        }

        // 构造数据输入
        StringBuilder userInput = new StringBuilder();

        // 分析目标
        userInput.append("分析需求：").append("\n");
        userInput.append(goal).append("\n");

        // 压缩数据
        userInput.append("原始数据：").append("\n");
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvData);

        // 持久化数据
        Chart chart = new Chart();
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setName(name);
        chart.setUserId(userId);
        chart.setChartType(chartType);
        chart.setStatus(TaskStatusEnum.WAITING.getCode());
        boolean save = chartService.save(chart);
        if (!save) {
            log.error("保存图表失败"+ chart);
        }

        CompletableFuture.runAsync(() -> {
            try {
                Chart update = new Chart();
                update.setStatus(TaskStatusEnum.RUNNING.getCode());
                update.setExecMessage("图表生成中...");
                update.setId(chart.getId());
                boolean result = chartService.updateById(update);
                if (!result) {
                    log.error("更新状态失败");
                }

                // 请求AI服务接口
                AiChatRequest chatRequest = AiManager.sendAiPost(BiConstant.BI_CODE, userInput.toString());

                String content = chatRequest.getContent();
                String[] genResults = content.split("====");
                String genChart = genResults[1].trim();
                // 加一层校验
                JSONUtil.parse(genChart);
                String genResult = genResults[2].trim();

                Chart finishedUpdate = new Chart();
                finishedUpdate.setId(chart.getId());
                finishedUpdate.setStatus(TaskStatusEnum.FINISHED.getCode());
                finishedUpdate.setExecMessage("图表生成完成！");
                finishedUpdate.setGenChart(genChart);
                finishedUpdate.setGenResult(genResult);
                boolean b = chartService.updateById(finishedUpdate);
                if (!b) {
                    log.error("更新图表成功状态失败");
                }
            } catch (Exception e){
                log.error("生成图表失败", e);
                Chart failedUpdate = new Chart();
                failedUpdate.setId(chart.getId());
                failedUpdate.setStatus(TaskStatusEnum.FAILED.getCode());
                failedUpdate.setExecMessage(e.getMessage());
                boolean b = chartService.updateById(failedUpdate);
                if (!b) {
                    log.error("更新图表失败状态失败");
                }
            }

        }, threadPoolExecutor);


        BiResponse biResponse = new BiResponse();

        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    @PostMapping("/genChartByAiMq")
    public BaseResponse<BiResponse> genChartByAiMq(@RequestPart("file") MultipartFile multipartFile,
                                                   GenChartByAiRequest genChartByAiRequest,
                                                   HttpServletRequest request) {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        User loginUser = userService.getLoginUser(request);

        ThrowUtils.throwIf(StrUtil.isBlank(goal), new RuntimeException("目标为空"));
        ThrowUtils.throwIf(ObjUtil.isNull(loginUser), new RuntimeException("用户未登录，请登陆！"));
        ThrowUtils.throwIf(StrUtil.isNotBlank(name) && name.length() > 100, new RuntimeException("名称过长"));

        // 数据校验
        String filename = multipartFile.getOriginalFilename();
        // 大小校验
        long size = multipartFile.getSize();
        // 10M限制
        final long maxSize = 1024 * 1024 * 10L;
        ThrowUtils.throwIf(size > maxSize, new RuntimeException("文件过大"));

        String suffix = FileUtil.getSuffix(filename);
        final List<String> validList = Arrays.asList("xls", "xlsx");
        ThrowUtils.throwIf(!validList.contains(suffix), new RuntimeException("所传文件非法"));

        // 针对每个用户进行限流
        Long userId = loginUser.getId();
        String limitPrefix = "mybi-genChartByAi";
        boolean isRateLimit = redisLimiterManager.doRateLimit(limitPrefix + userId.toString());
        ThrowUtils.throwIf(!isRateLimit, new RuntimeException("该账户已被限流，请24小时后再尝试！"));

        if (StringUtils.isNotBlank(chartType)) {
            goal = goal + "请使用：" + chartType;
        }


        String csvData = ExcelUtils.excelToCsv(multipartFile);

        // 持久化数据
        Chart chart = new Chart();
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setName(name);
        chart.setUserId(userId);
        chart.setChartType(chartType);
        chart.setStatus(TaskStatusEnum.WAITING.getCode());
        boolean save = chartService.save(chart);
        if (!save) {
            log.error("保存图表失败" + chart);
        }

        // 发送消息到队列
        producer.sendMessage(String.valueOf(chart.getId()));

        BiResponse biResponse = new BiResponse();

        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }
}
